package linc.fun.openai.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.crypto.BCUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author yqlin
 * @date 2023/5/6 21:02
 * @description
 */
@Component
public class RsaUtil {
    private String getPublicKey() {
        ClassPathResource path = new ClassPathResource("rsa/public_key.pem");
        InputStream is = path.getStream();
        PublicKey pubKey = BCUtil.readPemPublicKey(is);
        return Base64Encoder.encode(pubKey.getEncoded());
    }

    private String getPrivateKey() {
        ClassPathResource path = new ClassPathResource("rsa/private_key.pem");
        InputStream is = path.getStream();
        PrivateKey priKey = BCUtil.readPemPrivateKey(is);
        return Base64Encoder.encode(priKey.getEncoded());
    }


    /**
     * RSA加密
     */
    public String encrypt(String text) {
        RSA rsa = new RSA(null, this.getPublicKey());
        byte[] encrypted = rsa.encrypt(text.getBytes(), KeyType.PublicKey);
        return Base64.encode(encrypted);
    }

    /**
     * RSA解密
     */
    public String decrypt(String text) {
        RSA rsa = new RSA(this.getPrivateKey(), null);
        byte[] decrypted = rsa.decrypt(Base64.decode(text), KeyType.PrivateKey);
        return new String(decrypted);
    }
}
